package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

	@Autowired
	UserDao userDao;

	@Override
	public boolean login(String username, String password) {
		System.out.println("service_provide...u:"+username+" p:"+password);
		return "admin".equals(username) && "123".equals(password);
	}

	@Override
	public SysUser findByUsername(String username) {
		return userDao.findByUsername(username);
	}

	@Override
	@Transactional
	public void add(SysUser sysUser, Integer[] roleIds) {
		userDao.add(sysUser);
		if (sysUser.getId()!=null&&roleIds!=null&&roleIds.length>0){
			for (Integer roleId : roleIds) {
				//定义一个新的方法维护两者的关系
				userDao.addRelation(sysUser.getId(),roleId);
			}
		}
	}

	@Override
	public PageResult findPage(QueryPageBean queryPageBean) {
		PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
		//开始条件查询
		Page<SysUser> page=userDao.findByCondition(queryPageBean.getQueryString());
		//返回结果
		return new PageResult(page.getTotal(),page);
	}

	@Override
    @Transactional
	public void delById(Integer id) {
	userDao.delRoleRelation(id);
		userDao.delRoleRelation(id);
		userDao.delById(id);
	}

	@Override
	public SysUser findById(Integer id) {
		return userDao.findById(id);
	}

	@Override
	public List<Integer> findRoleIdsById(Integer id) {
		return userDao.findRoleIdsById(id);
	}

	@Override
	@Transactional
	public void edit(SysUser sysUser, Integer[] roleIds) {
		userDao.edit(sysUser);
		userDao.delRoleRelation(sysUser.getId());
		if (sysUser.getId()!=null&&roleIds!=null&&roleIds.length>0){
			for (Integer roleId : roleIds) {
				userDao.addRelation(sysUser.getId(),roleId);
			}
		}
	}
}

